import * as echarts from 'echarts'

/**
 * @description 绘制饼图
 * @param {HTMLElement} dom
 * @param {Array} data -渲染参数
 */
function drewPie(
  dom = '',
  data = [{ value: 100, name: 'item', unit: 'kwh' }],
) {
  if (!dom || !data || !data.length) return

  /**
   * @see https://echarts.apache.org/examples/zh/editor.html?c=pie-doughnut
   */
  const pieChart = echarts.init(dom)
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      type: 'scroll',
      top: 'middle',
      right: '5%',
      selectedMode: true,
      itemWidth: 10,
      itemHeight: 10,
      formatter: (name) => {
        return `${name} ${data.filter((i) => { return i.name === name })[0].value} ${data.filter((i) => { return i.name === name })[0].unit}`
      },
    },
    series: [
      {
        center: ['35%', '50%'],
        name: '分项用能',
        type: 'pie',
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: false,
          },
        },
        labelLine: {
          show: false,
        },
        data,
      },
    ],
  }

  pieChart.setOption(option)

  window.addEventListener('resize', () => {
    pieChart.resize()
  })
}

export { drewPie }
